package com.example.springboot.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;
import com.example.springboot.common.AliPayConfig;
import com.example.springboot.common.AuthAccess;
import com.example.springboot.controller.dto.AliPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能：

 * 日期：2024/3/11 17:12
 */

@RestController
@RequestMapping("/alipay")
public class AliPayController {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrdersProductMapper ordersProductMapper;
    @Autowired
    private ProductMapper productMapper;

    @Resource
    AliPayConfig aliPayConfig;
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "utf-8";
    private static final String SIGN_TYPE = "RSA2";

    @AuthAccess
    @GetMapping("/pay") // &subject=xxx&traceNo=xxx&totalAmount=xxx
    public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
                + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
                + "\"subject\":\"" + aliPay.getSubject() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }


    @AuthAccess
    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String number = params.get("out_trade_no");
            String paymentTime = params.get("gmt_payment");
            String alipayNo = params.get("trade_no");
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                // 获取订单的所有信息,根据订单的订单号
                Orders orders = ordersMapper.selectByNumber(number);
                Integer ordersId = orders.getId();
                // 对现在的数据表的话，支付成功后，
                // 我需要把订单表中的
                // pay_status改为1，
                // status改为2
                // payment_time改为当前的时间
                // alipay_no改为支付宝交易凭证号
                orders.setPayStatus(1);
                orders.setStatus(2);
                orders.setPaymentTime(new Date());
                orders.setAlipayNo(alipayNo);
                // 更新订单未已支付
                ordersMapper.update(orders);
                // 然后更新订单和商品的关系表
                Integer status = 1;
                ordersProductMapper.updateStatusByOrdersId(ordersId, status);
                // 更新商家的余额
                // 这里需要调用接口，把余额加上支付的金额，并更新到商家表中
//                List<OrdersProduct> ordersProductsDB = ordersProductMapper.selectByOrdersId(ordersId);
//                List<OrdersProduct> ordersProducts = ordersProductsDB.stream().distinct().collect(Collectors.toList());
//                for (OrdersProduct ordersProduct : ordersProducts) {
//                    Integer status1 = ordersProduct.getStatus();
//                    if (status1 == 1) {
//
//                    }
//                    Store store = ordersProduct.getStore();
//
//                }

            }
        }
        return "success";
    }
}
